import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
      config.headers['Authorization'] = `JWT  ${getToken()}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // code为非200是抛错 可结合自己业务进行修改
    if (res.code !== 200) {
      const errMsg = res.message || '请求失败'
      Message({
        message: errMsg,
        type: 'error',
        duration: 5 * 1000
      })

      // 50008:非法的token;  50014:Token 过期了;
      if (res.code === 403 || res.code === 401) {
        // to re-login
        MessageBox.confirm('您已登出，可以取消继续留在该页面，或者重新登录', '确认登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(errMsg))
    } else {
      return res
    }
  },
  // 请求非200的抛错
  error => {
    const { message } = error.response.data
    if (message === 'Signature has expired.' || message === 'Error decoding signature.') {
      Message({
        message: '认证过期，请重新登陆.',
        type: 'info',
        duration: 5 * 1000
      })
      // 页面过期刷新当前页重新登陆
      window.location.reload()
    } else {
      if (error.response.data.code === 401) {
        Message({
          message: message,
          type: 'info',
          duration: 5 * 1000
        })
      } else if (error.response.data.code === 403) {
        Message({
          message: message,
          type: 'warning',
          duration: 5 * 1000
        })
      } else {
        Message({
          message: message || '接口错误',
          type: 'error',
          duration: 5 * 1000
        })
      }
    }
    return Promise.reject(error)
  }
)

export default service
